package fr.ordre66.vlcs.ws;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import com.sun.jersey.core.util.Base64;

import fr.ordre66.vlcs.dto.Upload;
import fr.ordre66.vlcs.services.IUploadManager;

@Path("upload")
@Service("uploadWs")
public class UploadWs {

	@Autowired IUploadManager uploadManager;
	
	@POST
	@Path("/img")
	public String uploadImg(byte[] bytes) {
		System.out.println("Methode uploadImg");

		org.springframework.security.core.userdetails.User user;
		user = (org.springframework.security.core.userdetails.User)
					SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		System.out.println("taille de l'img: " + bytes.length+ " pour le user: " + user.getUsername());
		Upload u = new Upload();
		u.setFile(bytes);
		u.setLogin(user.getUsername());
		u.setType("img");
		
		uploadManager.uploadMedia(u);
		
		return "OK";
	}

	@GET
	@Path("img")
	@Produces("image/jpeg")
	public byte[] getLastImg() throws Exception {
		
		org.springframework.security.core.userdetails.User user;
		user = (org.springframework.security.core.userdetails.User)
					SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		byte[] f = uploadManager.getLastImage(user.getUsername());
		System.out.println("Taille de l'img à afficher: " + f.length);
		
		return Base64.encode(f);
	}

	@POST
	@Path("/video")
	public String uploadVideo(byte[] bytes) {
		System.out.println("Methode uploadVideo");

		org.springframework.security.core.userdetails.User user;
		user = (org.springframework.security.core.userdetails.User)
					SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		System.out.println("taille de la video: " + bytes.length+ " pour le user: " + user.getUsername());
		
		if(bytes.length > 10000000)
			return "Video too big (max 10000000 octets)";
		
		Upload u = new Upload();
		u.setFile(bytes);
		u.setLogin(user.getUsername());
		u.setType("video");
		
		uploadManager.uploadMedia(u);
		
		return "OK";
	}

	@GET
	@Path("videos/{keyID}")
	@Produces("video/x-flv")
	public byte[] getVideo(@PathParam("keyID") String keyID) throws Exception {
		
		System.out.println("retrieve video with keyID: " + keyID);
		keyID = keyID.substring(0, keyID.indexOf("."));
		System.out.println("retrieve video with keyID: " + keyID);
		org.springframework.security.core.userdetails.User user;
		user = (org.springframework.security.core.userdetails.User)
					SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		byte[] f = uploadManager.getVideo(user.getUsername(), new Long(keyID));
		System.out.println("Taille de l'img à afficher: " + f.length);
		
		return f;
	}
}
